package com.kate.cloud.shiro.web;


import com.kate.cloud.shiro.converter.UserFrom2UserDTOConverter;
import com.kate.cloud.shiro.dto.UserDTO;
import com.kate.cloud.shiro.entity.JzUser;
import com.kate.cloud.shiro.enums.ResultEnum;
import com.kate.cloud.shiro.exception.UserException;
import com.kate.cloud.shiro.from.UserFrom;
import com.kate.cloud.shiro.service.UserService;
import com.kate.cloud.shiro.util.ResultVOUtil;
import com.kate.cloud.shiro.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import java.util.HashMap;

import java.util.Map;


/**
 * Created by 李金照 on 2017/12/13.
 *
 * @author 金照
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api(value = "user",description = "用户相关API")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "list",produces = MediaType.APPLICATION_JSON_VALUE,httpMethod = "GET")
    @GetMapping("/list")
    @RequiresPermissions("sys:edit:user")
    public ResultVO<JzUser> list() {
        JzUser user = userService.selectUser("1");
        return ResultVOUtil.success(user);
    }

    @ApiOperation(value = "create",produces = MediaType.APPLICATION_JSON_VALUE,httpMethod = "POST")
    @PostMapping("/create")
    public ResultVO<Map<String,String>> create(@Valid @RequestBody UserFrom userFrom, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【创建用户】参数不正确，userFrom={}",userFrom);
            throw  new UserException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }
        UserDTO userDTO = UserFrom2UserDTOConverter.convert(userFrom);


        userService.createUser(userDTO);

        Map<String,String> map = new HashMap<>();
        map.put("id","123");
        return ResultVOUtil.success(map);
    }
}
